<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      const urls = []

      const base_url = 'https://jsonplaceholder.typicode.com/todos'

      for (let i = 1; i <= 50; i++) {
        urls.push(`${base_url}/${i}`)
      }

      handleRequest(urls, 8).then((res) => {
        console.log(res)
      })

      // 并发请求
      function handleRequest(urls, num) {
        return new Promise((resolve) => {
          if (urls.length === 0) {
            resolve([])
            return
          }

          const results = []
          let index = 0
          let count = 0

          // 发送请求
          async function request() {
            if (index === urls.length) {
              return
            }

            const index_current = index
            const url = urls[index++]
            try {
              results[index_current] = await fetch(url)
            } catch (err) {
              results[index_current] = err
            } finally {
              count++
              if (count === urls.length) {
                console.log(`请求执行完成，一共是${urls.length}个请求`)
                resolve(results)
              }
              // 判断请求是否完成
              request()
            }
          }

          for (let i = 0; i < num; i++) {
            request()
          }
        })
      }
    </script>
  </body>
</html>
